package hlhj.fhp.supreme.customview;

import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import fhp.hlhj.giantfold.utils.LogUtil;
import hlhj.fhp.supreme.R;

/**
 * Created by Administrator on 2018\5\31 0031.
 */

public class HorizontalScorllTextView extends HorizontalScrollView implements Runnable{

    int currentScrollX = 0;// 当前滚动的位置
    TextView tv;

    public HorizontalScorllTextView(Context context) {
        super(context);
        initView(context);
    }

    public HorizontalScorllTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public HorizontalScorllTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    void initView(Context context){
        View v = LayoutInflater.from(context).inflate(R.layout.scroll_layout, null);
        v.setOverScrollMode(OVER_SCROLL_ALWAYS);
        ((ScrollView) v).setScrollBarSize(0);
        tv = (TextView)v.findViewById(R.id.tv_video_name);
        this.addView(v);
    }

    public void setText(String text){
        tv.setText(text);
        startScroll();
    }

    private void startScroll(){
        this.removeCallbacks(this);
        post(this);
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        currentScrollX ++;// 滚动速度
        scrollTo(currentScrollX, 0);
        LogUtil.INSTANCE.log(currentScrollX+"----"+getCharacterWidth(tv));
        if (currentScrollX >= getCharacterWidth(tv)*110) {
            scrollTo(0, 0);
            currentScrollX = 0;
        }
        postDelayed(this, 10);
    }
    // 获取每个字符的宽度主方法：
    public float getCharacterWidth(String text, float size) {
        if (null == text || "".equals(text))
            return 0;
        float width = 0;
        Paint paint = new Paint();
        paint.setTextSize(size);
        float text_width = paint.measureText(text);// 得到总体长度
        width = text_width / text.length();// 每一个字符的长度
        return width;
    }
    public float getCharacterWidth(TextView tv) {
        if (null == tv)
            return 0f;
        return getCharacterWidth(tv.getText().toString(), tv.getTextSize())
                * tv.getScaleX();
    }
}